package com.winshare.saleAssistant.service.impl;

import com.winshare.saleAssistant.constant.ProductStatus;
import com.winshare.saleAssistant.dao.ProductMapper;
import com.winshare.saleAssistant.dao.StaffMapper;
import com.winshare.saleAssistant.domain.entity.ProductDO;
import com.winshare.saleAssistant.domain.entity.ProductModuleContentDO;
import com.winshare.saleAssistant.domain.entity.StaffDO;
import com.winshare.saleAssistant.domain.entity.StatisticsDO;
import com.winshare.saleAssistant.domain.query.ProductPreviewQuery;
import com.winshare.saleAssistant.domain.query.ProductQuery;
import com.winshare.saleAssistant.domain.dto.req.*;
import com.winshare.saleAssistant.domain.dto.resp.ProductPreviewDTO;
import com.winshare.saleAssistant.domain.dto.resp.ProductRespDTO;
import com.winshare.saleAssistant.exception.BusinessException;
import com.winshare.saleAssistant.mapper.ProductMapStruct;
import com.winshare.saleAssistant.service.OrganizationService;
import com.winshare.saleAssistant.service.ProductService;
import com.winshare.saleAssistant.service.StatisticsService;
import com.winshare.saleAssistant.util.Page;
import com.winshare.saleAssistant.util.RequestHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ProductServiceImpl implements ProductService {

    private final ProductMapper productMapper;

    private final StatisticsService statisticsService;

    private final StaffMapper staffMapper;

    private final OrganizationService organizationService;

    public ProductServiceImpl(StaffMapper staffMapper, ProductMapper productMapper,
                              StatisticsService statisticsService, OrganizationService organizationService) {
        this.staffMapper = staffMapper;
        this.productMapper = productMapper;
        this.statisticsService = statisticsService;
        this.organizationService = organizationService;
    }

    @Override
    public void save(ProductCreateDTO productCreateDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductCreateDTO(productCreateDTO);
        if (checkProductCategoryAndProductNameExist(productDO)) {
            throw new BusinessException("相同分类下面不能存在相同的产品");
        }
        productDO.setStatus(ProductStatus.draft);
        productDO.setCreator(RequestHolder.getCurrentUser().getStaffName());
        productDO.setCreateTime(LocalDateTime.now().toString());
        productDO.setOrgId(RequestHolder.getCurrentUser().getOrgId());
        productMapper.saveProduct(productDO);
    }

    @Override
    public void update(ProductUpdateDTO productUpdateDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductUpdateDTO(productUpdateDTO);
        if (checkProductCategoryAndProductNameExist(productDO)) {
            throw new BusinessException("相同分类下面不能存在相同的产品");
        }
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        if (4 == productDOInSql.getStatus()) {
            throw new BusinessException("已发布或审核通过的文章不能被修改");
        }
        List<ProductModuleContentDO> productModuleContentDOList = productDO.getProductModuleContentList();
        if (!CollectionUtils.isEmpty(productModuleContentDOList)) {
            productMapper.deleteProductModuleContent(productDO, productModuleContentDOList.get(0).getPattern());
            productMapper.batchInsertProductModuleContent(productModuleContentDOList);
        }
        productMapper.updateProduct(productDO);
    }

    @Override
    public void delete(ProductIdDTO productIdDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductIdDTO(productIdDTO);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        if (ProductStatus.passed == productDOInSql.getStatus().intValue() || ProductStatus.auditing == productDOInSql.getStatus().intValue()) {
            throw new BusinessException("只有草稿或已被驳回状态的产品才能被删除");
        }

        productMapper.deleteProduct(productDO);
    }

    @Override
    public Page<ProductRespDTO> getProductList(ProductQueryDTO productQueryDTO) {
        ProductQuery productQuery = ProductMapStruct.INSTANCE.fromProductQueryDTO(productQueryDTO);
        productQuery.setOffsetIndex(productQueryDTO.getOffsetIndex());
        if (Objects.equals(RequestHolder.getCurrentUser().getSourceType(), "mini")) {
            productQuery.setOrgIdList(null);
        } else {
            List<Integer> orgIdList = organizationService.getChildrenOrgList(RequestHolder.getCurrentUser().getOrgId(), null);
            productQuery.setOrgIdList(orgIdList);
        }
        int totalCount = productMapper.queryProductCount(productQuery);
        Integer pageIndex = productQueryDTO.getPageIndex();
        Integer pageSize = productQueryDTO.getPageSize();
        if (0 == totalCount) {
            return new Page<>(pageIndex, pageSize, totalCount, new ArrayList<>());
        }
        List<ProductDO> productDOList = productMapper.findProductListByConditions(productQuery);
        List<ProductRespDTO> productRespDTOList = ProductMapStruct.INSTANCE.fromProductDOList(productDOList);
        return new Page<>(pageIndex, pageSize, totalCount, productRespDTOList);
    }

    @Override
    public void cancelProduct(ProductIdDTO productIdDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductIdDTO(productIdDTO);
        ProductDO productInSql = productMapper.getProduct(productDO);
        if (null == productInSql) {
            throw new BusinessException("当前产品不存在。");
        }
        if (productInSql.getStatus().intValue() == ProductStatus.passed) {
            if (Objects.equals(RequestHolder.getCurrentUser().getStaffName(), productInSql.getIssuePerson())) {
                productDO.setStatus(ProductStatus.auditing);
            } else {
                throw new BusinessException("当前产品只能由审核人撤回");
            }

        } else if (productInSql.getStatus().intValue() == ProductStatus.auditing) {
            if (Objects.equals(RequestHolder.getCurrentUser().getStaffName(), productInSql.getIssuePerson()) || StringUtils.isEmpty(productInSql.getIssuePerson())) {
                productDO.setStatus(ProductStatus.draft);
            } else {
                throw new BusinessException("当前产品只能由审核人撤回");
            }
        } else {
            throw new BusinessException("当前产品已经为编辑状态！");
        }
        productMapper.updateProduct(productDO);
    }

    @Override
    public ProductPreviewDTO previewProduct(ProductPreviewQueryDTO productPreviewQueryDTO) {
        ProductPreviewQuery productPreviewQuery = ProductMapStruct.INSTANCE
                .fromProductPreviewQueryDTO(productPreviewQueryDTO);
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductPreviewQuery(productPreviewQuery);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        if (null == productDOInSql) {
            throw new BusinessException("你预览的产品不存在。");
        }
        productPreviewQuery.setProductCategoryId(productDOInSql.getProductCategoryId());
        List<ProductModuleContentDO> productModuleContentDOList = new ArrayList<>();
        if (CollectionUtils.isEmpty(productPreviewQuery.getModuleIdList())) {
            productModuleContentDOList = productMapper.getProductModuleContent(productPreviewQuery);
        } else {
            productModuleContentDOList = productMapper.getProductModuleContentByConditions(productPreviewQuery.getId(),
                    productPreviewQuery.getProductCategoryId(), productPreviewQuery.getModuleIdList(), productPreviewQuery.getPattern());
        }

        productDOInSql.setProductModuleContentList(productModuleContentDOList);
        ProductPreviewDTO productPreviewDTO = ProductMapStruct.INSTANCE
                .fromProductDOToProductPreviewDTO(productDOInSql);
        return productPreviewDTO;
    }

    @Override
    public void submitProduct(ProductIdDTO productIdDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductIdDTO(productIdDTO);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        if (null == productDOInSql) {
            throw new BusinessException("你提交的产品不存在。");
        }
        productDO.setCreator(RequestHolder.getCurrentUser().getStaffName());
        if (productDOInSql.getStatus().intValue() == ProductStatus.draft ||
                productDOInSql.getStatus().intValue() == ProductStatus.rejected) {
            productDO.setStatus(ProductStatus.auditing);
            productMapper.updateProduct(productDO);
            return;
        }
        throw new BusinessException("只有草稿或被驳回状态的产品才可以提交审核");
    }

    @Override
    public void agreeIssueProduct(ProductIdDTO productIdDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductIdDTO(productIdDTO);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        if (null == productDOInSql) {
            throw new BusinessException("当前产品不存在。");
        }
        if (productDOInSql.getStatus().intValue() == ProductStatus.auditing) {
            productDO.setStatus(ProductStatus.passed);
            // 审核人
            productDO.setIssuePerson(RequestHolder.getCurrentUser().getStaffName());
            // 审核时间
            productDO.setIssueTime(LocalDateTime.now().toString());
            productMapper.updateProduct(productDO);
            return;
        }
        throw new BusinessException("只有审核中的产品才能执行此操作。");
    }

    @Override
    public void agreeNoIssueProduct(ProductIdDTO productIdDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductIdDTO(productIdDTO);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        if (null == productDOInSql) {
            throw new BusinessException("当前产品不存在。");
        }
        if (productDOInSql.getStatus().intValue() == ProductStatus.auditing) {
            // 审核人
            productDO.setIssuePerson(RequestHolder.getCurrentUser().getStaffName());
            // 审核时间
            productDO.setIssueTime(LocalDateTime.now().toString());
            productDO.setStatus(ProductStatus.rejected);
            productMapper.updateProduct(productDO);
            return;
        }
        throw new BusinessException("只有审核中的产品才能执行此操作。");
    }

    @Override
    public void updateProductSort(ProductSortDTO productSortDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductSortDTO(productSortDTO);
        productMapper.updateProduct(productDO);
    }

    @Override
    public ProductRespDTO getProductDetail(BaseIdDTO baseIdDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromBaseIdDTO(baseIdDTO);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        if (null == productDOInSql) {
            throw new BusinessException("当前产品不存在。");
        }
        ProductRespDTO productRespDTO = ProductMapStruct.INSTANCE.fromProductDO(productDOInSql);
        return productRespDTO;
    }

    @Override
    public void addReadCount(ProductReadCountDTO productReadCountDTO) {
        productReadCountDTO.validatePattern();
        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductReadCountDTO(productReadCountDTO);
        productMapper.addReadCount(productDO);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        StatisticsDO statisticsDO = new StatisticsDO();
        statisticsDO.setType2(productReadCountDTO.getPattern());
        statisticsDO.setType1("产品");
        statisticsDO.setObjId(productDOInSql.getId());
        statisticsDO.setReadCount(1);
        statisticsDO.setObjName(productDOInSql.getProductName());
        statisticsService.saveStatistic(statisticsDO);

        StaffDO staffDO = RequestHolder.getCurrentUser();
        StaffDO staffDOInSql = staffMapper.queryByStaff(staffDO);
        staffDOInSql.setReadCount(staffDOInSql.getReadCount() + 1);
        staffMapper.updateStaff(staffDOInSql);
    }

    @Override
    public void addPromotionTimes(BaseIdDTO baseIdDTO) {
        ProductDO productDO = ProductMapStruct.INSTANCE.fromBaseIdDTO(baseIdDTO);
        productMapper.addPromotionTimes(productDO);
        ProductDO productDOInSql = productMapper.getProduct(productDO);
        StatisticsDO statisticsDO = new StatisticsDO();
        statisticsDO.setPromotionCount(1);
        statisticsDO.setType2("宣传模式");
        statisticsDO.setType1("产品");
        statisticsDO.setObjId(productDOInSql.getId());
        statisticsDO.setObjName(productDOInSql.getProductName());
        statisticsDO.setPromotionCount(1);
        statisticsService.saveStatistic(statisticsDO);

        StaffDO staffDO = RequestHolder.getCurrentUser();
        StaffDO staffDOInSql = staffMapper.queryByStaff(staffDO);
        staffDOInSql.setPromotionCount(staffDOInSql.getPromotionCount() + 1);
        staffMapper.updateStaff(staffDOInSql);
    }

    @Override
    public void releaseProduct(ProductIdDTO productIdDTO) {
//        ProductDO productDO = ProductMapStruct.INSTANCE.fromProductIdDTO(productIdDTO);
//        ProductDO productDOInSql = productMapper.getProduct(productDO);
//        if(null == productDOInSql) {
//            throw new BusinessException("当前产品不存在。");
//        }
//        if(productDOInSql.getStatus().intValue() == ProductStatus.passed) {
//            productDO.setStatus(ProductStatus.released);
//            productDO.setIssueTime(LocalDateTime.now().toString());
//            productMapper.updateProduct(productDO);
//            return;
//        }
        throw new BusinessException("此接口作废。");
    }

    private boolean checkProductCategoryAndProductNameExist(ProductDO productDO) {
        return productMapper.countByProductCategoryAndName(productDO) > 0;
    }
}
